package com.inspur.cloud.service.dataspace;

import com.inspur.cloud.dao.dataspace.HdfsResourceDao;
import com.inspur.cloud.dao.dataspace.UserDao;
import com.inspur.cloud.dao.dataspace.UserResourceRelationDao;
import com.inspur.cloud.entity.dataspace.HdfsResourceEntity;
import com.inspur.cloud.entity.dataspace.UserEntity;
import com.inspur.cloud.entity.dataspace.UserResourceRelationEntity;
import com.inspur.cloud.entity.dataspace.ao.resource.HdfsAO;
import com.inspur.cloud.entity.dataspace.common.OpEntityResult;
import com.inspur.cloud.entity.dataspace.common.PageReqParam;
import com.inspur.cloud.entity.dataspace.common.PageResult;
import com.inspur.cloud.entity.dataspace.dto.HdfsInfo;
import com.inspur.cloud.entity.dataspace.vo.HdfsReq;
import com.inspur.cloud.entity.dataspace.vo.HdfsVO;
import com.inspur.cloud.entity.dataspace.vo.auth.AuthInfoVO;
import com.inspur.cloud.entity.dataspace.vo.auth.AuthUpdateVO;
import com.inspur.cloud.enums.PermissionEnum;
import com.inspur.cloud.enums.QuotaEnum;
import com.inspur.cloud.enums.ResourceTypeEnum;
import com.inspur.cloud.exception.ApiException;
import com.inspur.cloud.security.AuthorizationHelper;
import com.inspur.cloud.util.StringUtil;
import com.inspur.cloud.util.TConstants;
import com.inspur.cloud.util.UtilTenant;
import org.apache.commons.lang.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import java.util.*;

@Service
public class HdfsManagerService {
    @Autowired
    private HdfsResourceService hdfsResourceService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserResRelationSerivce userResRelationSerivce;
    @Autowired
    private HdfsService hdfsService;
    @PersistenceContext
    private EntityManager em;
    @Autowired
    private RangerService rangerService;
    @Autowired
    private UserManagerService userManagerService;
    @Autowired
    private AuthService authService;

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> addRes(HdfsVO hdfsVO) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        UserEntity currentUser = AuthorizationHelper.getUser();
        Date now = new Date();
        HdfsResourceEntity hdfs = new HdfsResourceEntity();
        HdfsResourceEntity hdfsExist = hdfsResourceService.findFirstByUrl(hdfsVO.getUrl());
        if (hdfsExist != null) {
            return OpEntityResult.fail("要创建的资源路径已存在");
        }
        HdfsResourceEntity parent = null;
        if (AuthorizationHelper.isTenant()) {
            parent = hdfsResourceService.findHdfsResourceEntityById(hdfsVO.getParentId());
            if (parent == null) {
                return OpEntityResult.fail("父资源路径不存在");
            }
            //path是 /usr/chen33/abc parent 是 /usr/chen44
            if (!hdfsVO.getUrl().startsWith(parent.getUrl() + TConstants.DIRECTORY)) {
                return OpEntityResult.fail("没有权限新建资源:路径错误，越权创建");
            }
        }
        boolean isPublic = false;
        if (hdfsVO.getUrl().startsWith(TConstants.PUBLICPATH)) {
            isPublic = true;
        }
        String powerStr = authService.getSourceAuth(hdfsVO.getParentId(), currentUser.getId(), "HDFS");
        if (!(AuthorizationHelper.isAdmin(currentUser) && hdfsVO.getParentId() == 0 && isPublic)) {
            if (!powerStr.contains("write")) {
                throw new ApiException("无权新建资源");
            }
        }
        String allPower = PermissionEnum.getAllPermissionByType(1);
        hdfs.setStatus(1);
        hdfs.setLevel(StringUtil.getLevel(hdfsVO.getUrl()));
        String userName = currentUser.getName();
        String url = hdfsVO.getUrl();
        if (isPublic) {
            //创建公共资源
            hdfs.setOwner(1);
        } else {
            hdfs.setOwner(parent.getOwner());
        }
        hdfsService.makeDir(url);
        hdfsService.setOwner(url, userName, userName);


        Long quota = hdfsVO.getCapacity() * QuotaEnum.getSizeByType(hdfsVO.getUnit());

        hdfsService.setQuota(hdfsVO.getUrl(), quota, hdfsVO.getFileNum());
        hdfs.setUrl(hdfsVO.getUrl());
        hdfs.setParentId(hdfsVO.getParentId() == null ? 0 : hdfsVO.getParentId());
        hdfs.setCapacity(hdfsVO.getCapacity());
        hdfs.setUnit(hdfsVO.getUnit());
        hdfs.setFileNum(hdfsVO.getFileNum());
        hdfs.setCreator(currentUser.getId());
        hdfs.setInsDate(now);
        hdfs.setUpdDate(now);
        hdfsResourceService.saveAndFlush(hdfs);//资源入库
        if (parent != null) {
            parent.setUpdDate(now);
            hdfsResourceService.save(parent);
        }
        //只有管理员创建public资源的时候才授权
        if (AuthorizationHelper.isAdmin(currentUser) && (hdfsVO.getParentId() == 0) && hdfsVO.getType() == 1) {
            rangerService.setPermissionInRanger(ResourceTypeEnum.HDFS.name().toLowerCase(), hdfsVO.getUrl(), allPower, currentUser.getName());
            UserResourceRelationEntity ur = new UserResourceRelationEntity();
            ur.setResourceId(hdfs.getId());
            ur.setInsDate(now);
            ur.setUpdDate(now);
            ur.setStatus(1);
            ur.setUserId(currentUser.getId());
            ur.setResourceType(ResourceTypeEnum.HDFS.name());
            ur.setResourceContent(hdfs.getUrl());
            ur.setAuthor(allPower);
            ur.setResourceLevel(StringUtil.getLevel(hdfs.getUrl()));
            userResRelationSerivce.save(ur);
        }
        opEntityResult.setCode(1);
        opEntityResult.setMsg("hdfs资源创建成功");
        opEntityResult.setData(hdfs.getId());
        return opEntityResult;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> modifyRes(HdfsVO hdfsVO) {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        UserEntity currentUser = AuthorizationHelper.getUser();
        Date now = new Date();
        HdfsResourceEntity hdfs;
        Optional<HdfsResourceEntity> optional = hdfsResourceService.findById(hdfsVO.getResourceId());
        String path;
        if (!optional.isPresent()) {
            opEntityResult.setCode(-1);
            opEntityResult.setMsg("资源信息不存在于数据库");
            return opEntityResult;
        } else {
            hdfs = optional.get();
            path = hdfs.getUrl();
        }
        if (!currentUser.getId().equals(hdfs.getCreator())) {
            throw new ApiException("无权修改资源");
        }
        Long quotaData = hdfs.getCapacity() * QuotaEnum.getSizeByType(hdfs.getUnit());
        Long quota = hdfsVO.getCapacity() * QuotaEnum.getSizeByType(hdfsVO.getUnit());
        //如果修改了资源大小，大于数据库里存放的大小，那就要取判断余额了
//        if (quota > quotaData) {
//            Long unUsed = remain(hdfs.getParentId());
//            if (unUsed < quota) {
//                return OpEntityResult.fail("你修改了配额大小，但是剩余空间已不足分配");
//            }
//        }
        Long unUsed = remain(hdfs.getParentId());
        Long sum=unUsed+quotaData;
        if (quota > sum) {
                return OpEntityResult.fail("你修改了配额大小，但是剩余空间已不足分配");
        }

        OpEntityResult<Integer> result = remainFileNum(hdfs.getParentId());
        Integer unUsedFileNum = result.getData();
        Integer usedFileNum=hdfs.getFileNum();
        Integer newInput=hdfsVO.getFileNum();
        Integer sumFileNum=unUsedFileNum+usedFileNum;
        if (newInput>sumFileNum){
           return OpEntityResult.fail("你修改了配额大小，但是剩余空间已不足分配");
        }

        hdfs.setUpdDate(now);
        //有一个改动过数值后才调接口
        if (!hdfs.getFileNum().equals(hdfsVO.getFileNum()) || !quotaData.equals(quota)) {
            hdfsService.setQuota(path, quota, hdfsVO.getFileNum());
        }
        hdfs.setCapacity(hdfsVO.getCapacity());
        hdfs.setUnit(hdfsVO.getUnit());
        hdfs.setFileNum(hdfsVO.getFileNum());
        hdfsResourceService.saveAndFlush(hdfs);//资源入库

        if (hdfs.getParentId() != null && hdfs.getParentId() != 0) {//更新父资源操作时间
            HdfsResourceEntity parent = hdfsResourceService.findHdfsResourceEntityById(hdfs.getParentId());
            if (parent != null) {
                parent.setUpdDate(now);
                hdfsResourceService.save(parent);
            }
        }
        //只负责编辑
        if ((hdfsVO.getTenantList() != null && hdfsVO.getTenantList().size() > 0) ||
                (hdfsVO.getTenantIdList() != null && hdfsVO.getTenantIdList().size() > 0)) {
            hdfsVO.setResourceId(hdfs.getId());
            // disRes(hdfsVO);
        }
        opEntityResult.setCode(1);
        opEntityResult.setMsg("hdfs资源编辑成功");
        opEntityResult.setData(1);
        return opEntityResult;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> disRes(HdfsVO hdfsVO) {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        UserEntity currentUser = AuthorizationHelper.getUser();
        Optional<HdfsResourceEntity> optional = hdfsResourceService.findById(hdfsVO.getResourceId());
        HdfsResourceEntity hdfs;
        if (optional.isPresent()) {
            hdfs = optional.get();
        } else {
            return new OpEntityResult<>(-1, "指定的资源不存在", -1);
        }
        String auth = authService.getSourceAuth(hdfs.getId(), currentUser.getId(), "HDFS");
        if (StringUtils.isEmpty(auth)) {
            throw new ApiException("无权分配资源");
        }
        List<UserEntity> userList = new ArrayList<>();
        if (hdfsVO.getTenantIdList() != null && hdfsVO.getTenantIdList().size() > 0) {
            userList = userService.findByIdIn(hdfsVO.getTenantIdList());
        }
        if (hdfsVO.getUserIdList() != null && hdfsVO.getUserIdList().size() > 0) {
            userList.addAll(userService.findByIdIn(hdfsVO.getUserIdList()));
        }
        if (hdfsVO.getTenantList() != null && hdfsVO.getTenantList().size() > 0) {
            userList = userService.findByNameIn(hdfsVO.getTenantList());
        }
        if (hdfsVO.getUserList() != null && hdfsVO.getUserList().size() > 0) {
            userList.addAll(userService.findByNameIn(hdfsVO.getUserList()));
        }
        //将之前有权限的去掉，并给新用户家权限
        List<UserEntity> sonList = userManagerService.findUsersByParentId(currentUser.getId());
        AuthUpdateVO authUpdate = new AuthUpdateVO();
        authUpdate.setId(hdfs.getId());
        authUpdate.setType(ResourceTypeEnum.HDFS.name());
        List<AuthInfoVO> request = new ArrayList();
        for (UserEntity user : sonList) {
            Integer userId = user.getId();
            AuthInfoVO authInfoVO = new AuthInfoVO();
            UserResourceRelationEntity userResourceRelation = userResRelationSerivce.findByResourceIdAndUserIdAndResourceType(hdfs.getId(), userId, ResourceTypeEnum.HDFS.name());
            if (userResourceRelation != null) {
                authInfoVO.setId(userResourceRelation.getId());
            } else {
                authInfoVO.setId(null);
            }
            authInfoVO.setUserId(userId);
            if (userList.contains(user)) {
                authInfoVO.setAuth(auth);
            } else {
                authInfoVO.setAuth(null);
            }
            if (userResourceRelation != null || authInfoVO.getAuth() != null) {
                request.add(authInfoVO);
            }
        }
        authUpdate.setAuthList(request);
        authService.updateInfo(authUpdate);
        opEntityResult.setCode(1);
        if(UtilTenant.notEmptyHdfsDistribute(hdfsVO)) {
            opEntityResult.setMsg("hdfs资源分配成功");
        }else{
            opEntityResult.setMsg("分配已置空");
        }
        opEntityResult.setData(userList.size());
        return opEntityResult;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Boolean> delRes(Integer resourceId, Integer keepData) {
        OpEntityResult<Boolean> opEntityResult = new OpEntityResult<>();
        HdfsResourceEntity hdfs = hdfsResourceService.findHdfsResourceEntityById(resourceId);
        UserEntity currentUser = AuthorizationHelper.getUser();
        if (hdfs == null) {
            return OpEntityResult.of(-1, "指定的资源已经不存在");
        }
        String auth = authService.getSourceAuth(hdfs.getId(), currentUser.getId(), "HDFS");
        if (StringUtils.isEmpty(auth) || !auth.contains("write")) {
            if (!hdfs.getCreator().equals(currentUser.getId())) {
                throw new ApiException("无权删除该资源");
            }
        }

        //将之前有权限的去掉，并给新用户加权限
        List<UserResourceRelationEntity> userResourceRelationList = userResRelationSerivce.findByResourceIdAndResourceType(resourceId, ResourceTypeEnum.HDFS.name());
        AuthUpdateVO authUpdate = new AuthUpdateVO();
        authUpdate.setId(resourceId);
        authUpdate.setType(ResourceTypeEnum.HDFS.name());
        List<AuthInfoVO> request = new ArrayList();
        for (UserResourceRelationEntity relation : userResourceRelationList) {
            Integer userId = relation.getUserId();
            AuthInfoVO authInfoVO = new AuthInfoVO();
            authInfoVO.setId(relation.getId());
            authInfoVO.setUserId(userId);
            authInfoVO.setAuth(null);
            request.add(authInfoVO);
        }
        authUpdate.setAuthList(request);
        authService.updateInfo(authUpdate);

        String hdfsPath = hdfs.getUrl();
        String pathLike = hdfsPath + TConstants.DIRECTORY;
        List<Integer> ids = hdfsResourceService.findByUrlLike(pathLike);
        //把当前资源id加入
        ids.add(resourceId);
        int unboxKeepData = keepData.intValue();
        if (unboxKeepData == 1) {
            //处理资源表
            for (Integer hdfsId : ids) {
                HdfsResourceEntity tmpHdfs = hdfsResourceService.findHdfsResourceEntityById(hdfsId);
                if (tmpHdfs != null) {
                    tmpHdfs.setStatus(0);
                    hdfsResourceService.save(tmpHdfs);
                }
            }
        } else {
            //处理资源表
            hdfsService.removeDir(hdfsPath);
            hdfsResourceService.deleteByIdList(ids);
        }

        opEntityResult.setCode(1);
        opEntityResult.setMsg("hdfs资源已删除");
        opEntityResult.setData(true);
        return opEntityResult;
    }
    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> share(HdfsVO hdfsVO) {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        Date now = new Date();
        List<String> realList = new ArrayList<>();
        List<Integer> idList = new ArrayList<>();
        Optional<HdfsResourceEntity> optional = hdfsResourceService.findById(hdfsVO.getResourceId());
        UserEntity currentUser = AuthorizationHelper.getUser();
        if (!optional.isPresent()) {
            return new OpEntityResult<>(-1, "指定的资源不存在", 0);
        }
        HdfsResourceEntity hdfs = optional.get();
        String auth = authService.getSourceAuth(hdfs.getId(), currentUser.getId(), "HDFS");
        if (StringUtils.isEmpty(auth)) {
            throw new ApiException("无权分享资源");
        }
        if (hdfsVO.getTenantList() != null && hdfsVO.getTenantList().size() > 0) {
            for (String us : hdfsVO.getTenantList()) {
                if (!currentUser.getName().equals(us)) {
                    realList.add(us);//不能分享给自己，没意义
                }
            }
        }
        if (hdfsVO.getTenantIdList() != null) {
            for (Integer us : hdfsVO.getTenantIdList()) {
                if (!currentUser.getId().equals(us)) {
                    idList.add(us);
                }
            }
        }
        //将之前有权限的去掉，并给新用户家权限
        List<UserEntity> sonList = userManagerService.findUsersByParentId(TConstants.ADMIN_ID);
        AuthUpdateVO authUpdate = new AuthUpdateVO();
        authUpdate.setId(hdfs.getId());
        authUpdate.setType(ResourceTypeEnum.HDFS.name());
        List<AuthInfoVO> request = new ArrayList();
        for (UserEntity user : sonList) {
            //自己不处理
            if (user.getId().equals(currentUser.getId())) {
                continue;
            }
            Integer userId = user.getId();
            AuthInfoVO authInfoVO = new AuthInfoVO();
            UserResourceRelationEntity userResourceRelation = userResRelationSerivce.findByResourceIdAndUserIdAndResourceType(hdfs.getId(), userId, ResourceTypeEnum.HDFS.name());
            if (userResourceRelation != null) {
                authInfoVO.setId(userResourceRelation.getId());
            } else {
                authInfoVO.setId(null);
            }
            authInfoVO.setUserId(userId);
            if (realList.contains(user.getName()) || idList.contains(user.getId())) {
                authInfoVO.setAuth(auth);
            } else {
                authInfoVO.setAuth(null);
            }
            if (userResourceRelation != null || authInfoVO.getAuth() != null) {
                request.add(authInfoVO);
            }
        }
        authUpdate.setAuthList(request);
        authService.updateInfo(authUpdate);
        opEntityResult.setCode(1);
        opEntityResult.setData(realList.size() + idList.size());
        return opEntityResult;
    }


    public Long remain(Integer parentId) {
        Long quota = 0L;
        if (parentId == 0) {//顶级目录
            HdfsInfo hdfsInfo = hdfsService.getHDFSStatus();
            quota = hdfsInfo.getCapacity();
        } else {
            HdfsResourceEntity hdfs = hdfsResourceService.findHdfsResourceEntityById(parentId);
            if (hdfs == null) {
                return 0L;
            }
            quota = hdfs.getCapacity() * QuotaEnum.getSizeByType(hdfs.getUnit());//父目录总大小
        }
        //减去兄弟目录占用的大小
        Long used = getSpaceUsedByParentId(parentId);
        return quota - used;
    }

    public Long[] getRemain(Integer parentId) {
        Long capacity = remain(parentId);
        Long[] result = new Long[4];
        capacity /= 1024;
        result[0] = 0L;
        for (int i = 1; i < 4; i++) {
            capacity /= 1024;
            result[i] = capacity;
        }
        return result;
    }

    public OpEntityResult<Integer> remainFileNum(Integer parentId) {
        OpEntityResult<Integer> result = new OpEntityResult(1, "获取成功", -1);
        Integer quota = 0;
        if (parentId == 0) {//顶级目录，默认可以创建最大值
            quota = Integer.MAX_VALUE-1;
        } else {
            HdfsResourceEntity hdfs = hdfsResourceService.findHdfsResourceEntityById(parentId);
            if (hdfs == null) {
                return new OpEntityResult(-1, "未找到其父目录，请检查参数", 0L);
            }
            quota = hdfs.getFileNum()-1;//父目录文件数
        }
        Integer unused = quota;
        //减去兄弟占用的大小
        Integer used = getFileNumUsedByParentId(parentId);
        unused = quota - used;
        result.setData(unused);
        return result;
    }

    /**
     * 目录下已用空间
     *
     * @param parentId
     * @return
     */
    protected Long getSpaceUsedByParentId(Integer parentId) {
        String sql = "SELECT \n" +
                "   SUM(CASE WHEN unit = 1 THEN capacity*1024*1024 ELSE 0 END) AS sum1,\n" +
                "   SUM(CASE WHEN unit = 2 THEN capacity*1024*1024*1024 ELSE 0 END) AS sum2,\n" +
                "    SUM(CASE WHEN unit = 3 THEN capacity*1024*1024*1024*1024 ELSE 0 END) AS sum3 \n" +
                " FROM hdfs_resource WHERE parent_id=:parentId";
        Query query = em.createNativeQuery(sql);
        query.setParameter("parentId", parentId);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> result = query.getResultList();
        if (result != null && result.size() > 0) {
            Map used = result.get(0);
            Long sum1 = used.get("sum1") != null ? Long.valueOf(used.get("sum1").toString()) : 0L;
            Long sum2 = used.get("sum1") != null ? Long.valueOf(used.get("sum2").toString()) : 0L;
            Long sum3 = used.get("sum3") != null ? Long.valueOf(used.get("sum3").toString()) : 0L;
            return sum1 + sum2 + sum3;
        } else {
            return 0L;
        }

    }

    protected Integer getFileNumUsedByParentId(Integer parentId) {
        String sql = "SELECT  SUM(file_num) AS cnt FROM hdfs_resource WHERE parent_id=:parentId";
        Query query = em.createNativeQuery(sql);
        query.setParameter("parentId", parentId);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> result = query.getResultList();
        if (result != null && result.size() > 0) {
            Map used = result.get(0);
            Integer sum1 = used.get("cnt") != null ? Integer.valueOf(used.get("cnt").toString()) : 0;
            return sum1;
        } else {
            return 0;
        }

    }

    /**
     * 获取资源列表
     *
     * @param params
     * @return
     */
    public PageResult<HdfsAO> list(PageReqParam<HdfsReq> params) {
        Integer pageIndex = params.getPageIndex();
        Integer pageSize = params.getPageSize();
        HdfsReq hdfsReq = params.getReqParam();
        Integer level = 0;
        Integer parentId = hdfsReq.getResourceId();
        if (parentId != 0) {
            HdfsResourceEntity parentHdfs = hdfsResourceService.findHdfsResourceEntityById(parentId);
            if (parentHdfs == null) {
                throw new ApiException("父资源不存在");
            }
            level = parentHdfs.getLevel();
        }
        //根据层级添加/%，为了只匹配最后一层的路径
        StringBuffer preSql = new StringBuffer("/%/%");
        for (int i = 0; i < level; i++) {
            preSql.append("/%");
        }
        UserEntity currentUser = AuthorizationHelper.getUser();
        Integer tenantUserId = AuthorizationHelper.isUser(currentUser) ? currentUser.getParentId() : currentUser.getId();
        Specification<HdfsResourceEntity> specification = (Specification<HdfsResourceEntity>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(cb.equal(root.get("parentId"), hdfsReq.getResourceId()));
            list.add(cb.equal(root.get("status"), 1));
            String path = hdfsReq.getResourceName();
            if (!StringUtils.isEmpty(path)) {
                list.add(cb.like(root.get("url"), preSql.toString() + StringUtil.specialStr(path) + "%"));
            }
            if (hdfsReq.getType() == 1) {
                //公共的owner为1
                list.add(cb.equal(root.get("owner"), TConstants.ADMIN_ID));
            } else if (hdfsReq.getType() == 2) {
                //私有的owner为所在租户,admin另做处理
                if (AuthorizationHelper.isAdmin(currentUser)) {
                    list.add(cb.notEqual(root.get("owner"), TConstants.ADMIN_ID));
                } else {
                    list.add(cb.equal(root.get("owner"), tenantUserId));
                }

            } else if (hdfsReq.getType() == 3) {
                //共享owner既不为1也不为所在租户
                list.add(cb.notEqual(root.get("owner"), TConstants.ADMIN_ID));
                list.add(cb.notEqual(root.get("owner"), tenantUserId));
            }
            if (!AuthorizationHelper.isAdmin(currentUser)) {
                Subquery<UserResourceRelationEntity> subQuery = query.subquery(UserResourceRelationEntity.class);
                Root<UserResourceRelationEntity> subRoot = subQuery.from(UserResourceRelationEntity.class);
                subQuery.select(subRoot);
                List<Predicate> subList = new ArrayList<>();
                List<Predicate> subOrList = new ArrayList<>();
                subList.add(cb.equal(subRoot.get("userId"), currentUser.getId()));
                subOrList.add(cb.equal(subRoot.get("resourceContent"), root.get("url")));
                subOrList.add(cb.like(subRoot.get("resourceContent"), cb.concat(root.get("url"), "/%")));
                subOrList.add(cb.like(root.get("url"), cb.concat(subRoot.get("resourceContent"), "/%")));
                subList.add(cb.or(subOrList.toArray(new Predicate[subOrList.size()])));
                subQuery.where(cb.and(subList.toArray(new Predicate[subList.size()])));
                list.add(cb.exists(subQuery));
            }
            return cb.and(list.toArray(new Predicate[list.size()]));
        };
        //分页是从0开始而不是1，所以要减1
        Sort sort = new Sort(Sort.Direction.DESC, "updDate");
        Page<HdfsResourceEntity> findList = hdfsResourceService.findAll(specification, PageRequest.of(pageIndex - 1, pageSize, sort));
        PageResult<HdfsAO> result = new PageResult<>();
        List<HdfsAO> resultList = new ArrayList();
        //获取父资源的权限
        Integer resourceId = hdfsReq.getResourceId();
        UserResourceRelationEntity userResourceRelation = userResRelationSerivce.findByResourceIdAndUserIdAndResourceType(resourceId, currentUser.getId(), "HDFS");
        HdfsResourceEntity hdfsResourceEntity = hdfsResourceService.findHdfsResourceEntityById(resourceId);
        if (resourceId != 0) {
            while (userResourceRelation == null) {
                hdfsResourceEntity = hdfsResourceService.findHdfsResourceEntityById(hdfsResourceEntity.getParentId());
                if (hdfsResourceEntity == null) {
                    break;
                }
                userResourceRelation = userResRelationSerivce.findByResourceIdAndUserIdAndResourceType(hdfsResourceEntity.getId(), currentUser.getId(), "HDFS");
            }
        }
        String parentAuth = userResourceRelation == null ? null : userResourceRelation.getAuthor();
        for (HdfsResourceEntity hdfsResource : findList) {
            HdfsAO hdfs = new HdfsAO();
            BeanUtils.copyProperties(hdfsResource, hdfs);
            hdfs.setResourceId(hdfsResource.getId());
            UserEntity creator = userManagerService.findUserById(hdfsResource.getCreator());
            hdfs.setCreator(creator == null ? "" : creator.getName());
            UserEntity owner = userManagerService.findUserById(hdfsResource.getOwner());
            hdfs.setOwner(owner == null ? "" : owner.getName());
            String[] url = hdfsResource.getUrl().split(TConstants.DIRECTORY);
            hdfs.setUrl(url[url.length - 1]);
            UserResourceRelationEntity currentResource = userResRelationSerivce.findByResourceIdAndUserIdAndResourceType(hdfsResource.getId(), currentUser.getId(), "HDFS");
            if (currentResource == null || StringUtils.isEmpty(currentResource.getAuthor())) {
                hdfs.setPowerList(parentAuth);
            } else {
                hdfs.setPowerList(currentResource.getAuthor());
            }
            List<UserResourceRelationEntity> userList = userResRelationSerivce.findByResourceIdAndResourceType(hdfsResource.getId(), "HDFS");
            List<String> userResultList = new ArrayList();
            List<String> tenantResultList = new ArrayList();
            for (UserResourceRelationEntity relation : userList) {
                if (relation.getUserId().equals(currentUser.getId())) {
                    continue;
                }
                UserEntity tmpUser = userManagerService.findUserById(relation.getUserId());
                if (AuthorizationHelper.isTenant(tmpUser)) {
                    tenantResultList.add(tmpUser.getName());
                    continue;
                }
                if (AuthorizationHelper.isUser(tmpUser) && (currentUser.getId().equals(tmpUser.getParentId()) || AuthorizationHelper.isAdmin(currentUser))) {
                    userResultList.add(tmpUser.getName());
                }
            }
            hdfs.setTenantList(tenantResultList);
            hdfs.setUserList(userResultList);
            resultList.add(hdfs);

        }
        result.setPageList(resultList);
        result.setCount(findList.getTotalElements());
        result.setPageTotal(findList.getTotalPages());
        return result;
    }

    public boolean existPath(String path) {
        HdfsResourceEntity exist = hdfsResourceService.findFirstByUrl(path);
        return exist != null;
    }


}
